package com.example.iread.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.iread.R;
import com.example.iread.adapter.BookListAdapter;
import com.example.iread.bean.BookBean;
import com.example.iread.http.BookApi;
import com.example.iread.util.GsonUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

public class SearchResultActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        ImageButton btn_search_result_close = findViewById(R.id.btn_search_result_close);
        btn_search_result_close.setOnClickListener(v -> finish());

        TextView tv_empty = findViewById(R.id.tv_empty);
        RecyclerView rv_book_search = findViewById(R.id.rv_book_search);

        Intent intent = getIntent();
        String keyword = intent.getStringExtra("keyword");

        BookApi.search(keyword, res -> {
            Type type = TypeToken.getParameterized(List.class, BookBean.class).getType();
            List<BookBean> bookBeanList = GsonUtil.parseObject(res.data, type);

            if (bookBeanList == null || bookBeanList.size() == 0) return;

            tv_empty.setVisibility(View.GONE);
            rv_book_search.setVisibility(View.VISIBLE);

            rv_book_search.setLayoutManager(new LinearLayoutManager(this));

            BookListAdapter bookListAdapter = new BookListAdapter(this, bookBeanList);
            rv_book_search.setAdapter(bookListAdapter);
        });
    }
}